from app.models import Base

from sqlalchemy import Column, Integer, String, \
    Text, ForeignKey, DateTime, UniqueConstraint, \
        Index, Boolean, SmallInteger
from sqlalchemy.orm import relationship
from datetime import datetime

class User(Base):
    id = Column(Integer, primary_key=True)
    email = Column(String(24), unique=True, nullable=False)
    nickname = Column(String(24), unique=True)
    auth = Column(SmallInteger, default=1)
    _password = Column('password', String(100))

    role_id = Column(Integer, ForeignKey('role.id')) # 所属角色

    # userlogs = relationship('Userlog', backref='user')
    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    def check_password(self, raw):
        if not self._password:
            return False
        return check_password_hash(self._password, raw)

    @staticmethod
    def register_by_email(nickname, account, secret):
        user = User()
        user.nickname = nickname
        user.email = account
        user.password = secret    
        try:
            session = create_session()
            session.add(user)
            session.commit()
        finally:
            session.close()